import json
import time

import requests
import datetime

sess = requests.Session()
#################################
logname = "blpw.txt"
yanshi = 0.95
priceId = 626294
saleclassId = 1531323
showId = 11791500
consignee = "牛少波"
consigneePhone = "17733863156"
deliveryWay = "03"
viewerIdList = ["1804435532223098881"]
Authorization = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI2eWtLRmJVNTBUTUFjYng0Y1R6cS9Ob2FDUGhvUklkY3VOaDZnUG14N0Z4aExUSTQ3OFh1MnR6bTdkUDRmRlU9IiwiaXNzIjoicGxhdF9oNSIsImV4cCI6NDg3MDU0MzQ0NSwiaWF0IjoxNzE2OTQzNDQ1fQ.xZ4j7Vy_ccIBgKaauqNa_e6UjojSOuJte_cANJYHC6E"
#################################

headers = {
    "Host": "weixin.polyt.cn",
    "Connection": "keep-alive",
    "Theater": "971",
    "Atgc": "8eff40a352bea5d83a50c07741b280ee",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090b11) XWEB/9129 Flue",
    "Channel": "theatre_wx",
    "Accept": "*/*",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Referer": "https://weixin.polyt.cn/thh5/",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9"
}

proxies = {"http": None, "https": None}

url = "https://weixin.polyt.cn/platform-backend/good/project/detail/7076800"

res = sess.get(url, headers=headers, proxies=proxies)

js = res.json()
stime = datetime.datetime.now()
if js.get("data") and js.get("data").get("invoicingTime"):
    stime = datetime.datetime.fromtimestamp(js.get("data").get("invoicingTime") / 1000)
    stime -= datetime.timedelta(seconds=1)
print(stime.strftime("%Y-%m-%d %H:%M:%S"))
print("延时：" + str(yanshi))

while datetime.datetime.now() < stime:
    pass

time.sleep(yanshi)


def run(f_w):
    try:
        lock_seat = "https://weixin.polyt.cn/order/lock-seat-now"
        data = {
            "priceList": [{
                "num": 1,
                "priceId": priceId,
                "saleclassId": saleclassId
            }],
            "showId": showId,
            "activityId": "",
            "productId": ""
        }
        res = sess.post(lock_seat, headers=headers, data=json.dumps(data), proxies=proxies)
        js = res.json()
        f_w.write(json.dumps(js, indent=4, ensure_ascii=False, sort_keys=True))
        f_w.write("\n")
        if js.get("success"):
            data = {
                "consignee": consignee,
                "consigneePhone": consigneePhone,
                "deliveryWay": deliveryWay,
                "uuid": js.get("data"),
                "viewerIdList": viewerIdList
            }
            quick_order = "https://weixin.polyt.cn/platform-backend/order/quick-order"
            res = sess.post(quick_order, headers=headers, data=json.dumps(data), proxies=proxies)
            js = res.json()
            f_w.write(json.dumps(js, indent=4, ensure_ascii=False, sort_keys=True))
            f_w.write("\n")
            if js.get("success"):
                data = {
                    "page": 1,
                    "size": 1,
                    "orderStatus": "PEND_PAYMENT"
                }
                orders = "https://weixin.polyt.cn/platform-backend/order/orders"
                res = sess.post(orders, headers=headers, data=json.dumps(data), proxies=proxies)
                js = res.json()
                f_w.write(json.dumps(js, indent=4, ensure_ascii=False, sort_keys=True))
                f_w.write("\n")
                return True
            return False
        return False
    except Exception as e:
        f_w.write(str(e))
        print(e)
        f_w.write("\n")
    return False


with open(logname, "w") as f_w:
    for i in range(10):
        f_w.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") + "\n")
        if run(f_w):
            break
        time.sleep(0.2)
